package cc.ufinity.networkdiagnose.manager;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import android.util.Log;
import cc.ufinity.networkdiagnose.util.HttpUtils;
import cc.ufinity.networkdiagnose.util.StringUtils;

/**
 * Web登录及下线认证测试类
 * 
 * @author zhirong
 * 
 */
public final class UnicomWebAuthManager extends AbstractManager {

    private String userName;
    private String pwd;
    private String domain;
    private long startTime;
	private long endTime;

    private String loginUrl = "http://58.242.1.187:888/portalserver?action=login&pginfo=/twoversion/twologin.jsp&pgsuccess=/twoversion/indexed.jsp";
    private String logoutUrl = "http://58.242.1.187:888//portalserver?action=logout&un_=";
  //  private String timeUrl = "http://58.242.1.187:888//";
    private static final String TAG = "unicomWebAuth"; 
    

    public UnicomWebAuthManager( ) {
    }

    
    /**
     * 登录用户下线
     * 
     * @return TRUE or False
     */
    public boolean logout() {
        boolean success = false;
        HttpClient client = HttpUtils.getSSLHttpClient();
        try {
        	logoutUrl += userName;
        	long currTime = new Date().getTime();
        	logoutUrl += "&currTime=" + currTime;
        	HttpGet get = new HttpGet(logoutUrl + "?" + Math.random());
         //   HttpGet get = new HttpGet(logoutUrl + "?" + Math.random());
            HttpResponse response = client.execute(get);
            int sc = response.getStatusLine().getStatusCode();
            String content = EntityUtils.toString(response.getEntity());
            System.out.println("断开网络返回状态：" + sc);
            System.out.println("断开网络返回页面：" + content);
            if (sc == HttpStatus.SC_OK) {
                if (content.contains("1")) {
                	System.out.println("断开网络成功！");
                    success = true;
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "下线认证出错", e);
        } finally {
            client.getConnectionManager().shutdown();
        }
        return success;

    }
    /**
     * 登录认证
     */
    public boolean auth(String url, String userName, String pwd, String domain) {
         
    	System.out.println("url:"+url+"：用户名："+userName+"：密码："+pwd+"省："+domain);
    	System.out.println("开始web 认证");
        this.userName = userName;
        this.pwd = pwd;
        this.domain = domain;
        boolean success = false;
        HttpClient client = HttpUtils.getSSLHttpClient();
        HttpGet get = new HttpGet(url);
        try {
            HttpResponse response = client.execute(get);
            int sc = response.getStatusLine().getStatusCode();
            String result = EntityUtils.toString(response.getEntity());
            System.out.println("redirect返回结果，认证页面："+ result);
            Header []headers = response.getAllHeaders();
            System.out.println("redirect返回，认证页面cookies：");
            for(int i=0; i<headers.length; i++){
            	System.out.println(headers[i].getName() + ": " +headers[i].getValue());
            }
            
            if(sc == HttpStatus.SC_OK){
            	HttpPost post = new HttpPost(this.loginUrl);
            	post.setEntity(new UrlEncodedFormEntity(setRequestParams()));
            	response = client.execute(post);
            	sc = response.getStatusLine().getStatusCode();
            	System.out.println("认证返回状态：" + sc);
            	String content = EntityUtils.toString(response.getEntity());
            	System.out.println("认证返回页面："+ content);
            	if(sc == HttpStatus.SC_OK){
            		if(content.contains("当前登录号码")){
            			System.out.println("认证成功！");
            			success = true;
            		}
            	}
            }
            

        } catch (Exception e) {
            Log.e(TAG, "Web登陆认证发生错误：", e);
        } finally {
            client.getConnectionManager().shutdown();
        }
        return success;

        // return wh.CMCCLogin(userName, pwd);
    }

    public  boolean canGotoWeb()
    {
	    HttpClient client = HttpUtils.getSSLHttpClient(); 
        HttpGet get = new HttpGet("http://www.baidu.com");
        HttpResponse response;
		try {
			response = client.execute(get); int sc = response.getStatusLine().getStatusCode(); 
	         String content = EntityUtils.toString(response.getEntity());
	         System.out.println(content);
	         if (sc == HttpStatus.SC_OK) {
	             if (content.contains("百度一下，你就知道")) {
	                 return true;
	             }
	         }
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
    	return false;
    }

    /**
     * 根据服务器端返回的页面内容进行解析，判断用户是否登录成功.
     * 
     * @param responseContent
     *            服务器返回的页面内容
     */
    private boolean isLogin(String responseContent) {
        boolean res = true;
        if (!StringUtils.isEmpty(responseContent)) {
            if (responseContent.contains("登录失败")) {
                res = false;
            }
        }
        return res;
    }

    /**
     * 根据服务器端返回的页面内容解析，判断用户账号是否在别处登录为在线状�?��??
     * 
     * @param response
     */
    private boolean isOnline(String response) {
        boolean res = false;
        if (!StringUtils.isEmpty(response)) {
            if (response.contains("当前登录的用户已在线")) {
                res = true;
            }
        }
        return res;
    }

    private Map<String, String> parseLogonParams(String content, String tag, String attr) {
        Map<String, String> httpParams = null;
        Document doc = Jsoup.parse(content);
        try {
        	Element e = doc.select(tag).get(1);
            System.out.println("e:"+e.toString());
			// TODO: handle exception
	        if (e != null) {
	            String src = e.attr(attr);
	            System.out.println("scr"+src);
	           // requestUrl = src;
	            httpParams = StringUtils.parseURLChinaNet(src);
        } 
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println(e);
		}
        return httpParams;
    }
    
    
    private Map<String, String> parseLogonParamsLgout(String content, String tag, String attr) {
        Map<String, String> httpParams = new HashMap<String, String>();
        Document doc = Jsoup.parse(content);
        try {
        	for(int i=0; i<4; i++){
        		Element e = doc.select(tag).get(i);
              //   System.out.println("e:"+e.toString());
    			// TODO: handle exception
    	        if (e != null) {
    	            String value = e.attr(attr);
    	            String id = e.attr("id");
    	           //  System.out.println("id:"+id+"  value:"+value);
    	            httpParams.put(id, value);
        	}
        } 
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println(e);
		}
        return httpParams;
    }

    private String getAuthUrl(String content) {
        InputStream is = new ByteArrayInputStream(content.getBytes());
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));

        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                if (line.contains("http://221.130.132.1:8080")) {
                    int len = line.indexOf("http://");
                    int end = line.lastIndexOf('"');
                    line = line.substring(len, end);
                    sb.append(line);
                    Log.e(TAG, line);
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }

    private List<NameValuePair> setRequestParams() {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("username", userName ));
        params.add(new BasicNameValuePair("password", pwd ));
        params.add(new BasicNameValuePair("domain", domain ));
        return params;
    } 
    
	public long getStartTime() {
		return startTime;
	}

	public void setStartTime(long startTime) {
		this.startTime = startTime;
	}

	public long getEndTime() {
		return endTime;
	}

	public void setEndTime(long endTime) {
		this.endTime = endTime;
	}
    

}
